//标准状态是否废止
var standardStatus = [];
var seleceedButton;

var list = [
    {
        "name": "采矿业", "value": "采矿业",
        "class2":
            [{ "name": "煤炭开采和洗选业", "value": "煤炭开采和洗选业" },
            { "name": "石油和天然气开采业", "value": "石油和天然气开采业" },
            { "name": "黑色金属矿采选业", "value": "黑色金属矿采选业" },
            { "name": "有色金属矿采选业", "value": "有色金属矿采选业" },
            { "name": "非金属矿采选业", "value": "非金属矿采选业" },
            { "name": "开采专业及辅助性活动", "value": "开采专业及辅助性活动" },
            { "name": "其他采矿业", "value": "其他采矿业" }]
    },

    {
        "name": "制造业", "value": "制造业",
        "class2":
            [{ "name": "农副食品加工业", "value": "农副食品加工业" },
            { "name": "食品制造业", "value": "食品制造业" },
            { "name": "酒、饮料和精制茶制造业", "value": "酒、饮料和精制茶制造业" },
            { "name": "烟草制品业", "value": "烟草制品业" },
            { "name": "纺织业", "value": "纺织业" },
            { "name": "纺织服装、服饰业", "value": "纺织服装、服饰业" },
            { "name": "皮革、毛皮、羽毛及其制品和制鞋业", "value": "皮革、毛皮、羽毛及其制品和制鞋业" },
            { "name": "木材加工和木、竹、藤、棕、草制品业", "value": "木材加工和木、竹、藤、棕、草制品业" },
            { "name": "家具制造业", "value": "家具制造业" },
            { "name": "造纸和纸制品业", "value": "造纸和纸制品业" },
            { "name": "印刷和记录媒介复制业", "value": "印刷和记录媒介复制业" },
            { "name": "文教、工美、体育和娱乐用品制造业", "value": "文教、工美、体育和娱乐用品制造业" },
            { "name": "石油、煤炭及其他燃料加工业", "value": "石油、煤炭及其他燃料加工业" },
            { "name": "化学原料和化学制品制造业", "value": "化学原料和化学制品制造业" },
            { "name": "医药制造业", "value": "医药制造业" },
            { "name": "化学纤维制造业", "value": "化学纤维制造业" },
            { "name": "橡胶和塑料制品业", "value": "橡胶和塑料制品业" },
            { "name": "非金属矿物制品业", "value": "非金属矿物制品业" },
            { "name": "黑色金属冶炼和压延加工业", "value": "黑色金属冶炼和压延加工业" },
            { "name": "有色金属冶炼和压延加工业", "value": "有色金属冶炼和压延加工业" },
            { "name": "金属制品业", "value": "金属制品业" },
            { "name": "通用设备制造业", "value": "通用设备制造业" },
            { "name": "专用设备制造业", "value": "专用设备制造业" },
            { "name": "汽车制造业", "value": "汽车制造业" },
            { "name": "铁路、船舶、航空航天和其他运输设备制造业", "value": "铁路、船舶、航空航天和其他运输设备制造业" },
            { "name": "电气机械和器材制造业", "value": "电气机械和器材制造业" },
            { "name": "计算机、通信和其他电子设备制造业", "value": "计算机、通信和其他电子设备制造业" },
            { "name": "仪器仪表制造业", "value": "仪器仪表制造业" },
            { "name": "其他制造业", "value": "其他制造业" },
            { "name": "废弃资源综合利用业", "value": "废弃资源综合利用业" },
            { "name": "金属制品、机械和设备修理业", "value": "金属制品、机械和设备修理业" },
            ]
    },

    {
        "name": "电力、热力、燃气及水生产和供应业", "value": "电力、热力、燃气及水生产和供应业",
        "class2":
            [
                { "name": "电力、热力生产和供应业", "value": "电力、热力生产和供应业" },
                { "name": "燃气生产和供应业", "value": "燃气生产和供应业" },
                { "name": "水的生产和供应业", "value": "水的生产和供应业" },
            ]
    }
];

var _columns = [
    { checkbox: true },
    { field: 'id', title: '标示符', align: 'center', valign: 'middle' },
    {
        title: '序号', field: 'showId', align: 'center', valign: 'middle',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    { field: 'evaDate', title: '核算日期', sortable: true },
    { field: 'companyName', title: '企业名称', sortable: true },
    { field: 'class1', title: '门类', sortable: true },
    { field: 'class2', title: '所属行业', sortable: true },
    { field: 'companyType', title: '企业类型', sortable: true },
    { field: 'evaBasis', title: '评价依据', sortable: true },
    { field: 'evaUnit', title: '评价单位', sortable: true },
    { field: 'evaPerson', title: '评价人员', sortable: true },
    {
        field: 'state', title: '状态',
        formatter: function (value, row, index) {
            if (value == "填写中") {
                return "<span style='color:red'>填写中</span>";
            } else {
                return "<span style='color:green'>已完成</span>";
            }
        }
    },
    {
        field: 'operation', title: '操作',
        formatter: function (value, row, index) {
            var status;
            for (var i = 0; i < standardStatus.length; i++) {
                if (standardStatus[i].key == row.evaBasis) {
                    status = standardStatus[i].value;
                    break;
                }
            }
            if (status == '现行') {
                if (row.state == '填写中') {
                    return '<a href="#" mce_href="#" onclick="edit(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>编辑</a>';
                } else {
                    return '<a href="#" mce_href="#" onclick="view(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>查看</a> <a href="#" mce_href="#" onclick="edit(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>编辑</a> <a href="#" mce_href="#" onclick="exportTable(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>导出</a>';
                }
            } else {
                if (row.state == '填写中') {
                    return '废止标准 <a href="#" mce_href="#" onclick="view(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>查看</a>';
                } else {
                    return '废止标准 <a href="#" mce_href="#" onclick="view(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>查看</a> <a href="#" mce_href="#" onclick="exportTable(\'' + row.id + '\',\'' + row.evaBasis + '\',\'' + row.companyType + '\')"><i class="fa fa-edit" ></i>导出</a>';
                }
            }
        }
    },
]


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/entity_classified_standard/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            sortable: true,                     //是否启用排序
            sortOrder: "desc",                  //排序方式
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_add").click(function () {
            //初始化门类下拉框
            class1Init();

            seleceedButton = 'add';

            $('#company_name').val("");
            $('#class1').val("");
            $('#class2').val("");
            $('#company_type').val("");
            $('#eva_basis').val("");
            $('#eva_unit').val("");
            $('#eva_person').val("");
            document.getElementById('title').innerHTML = '添加一项评价量化标准';
            $('#data').modal();
            //时间组件加载
            $('#eva_date').val(getToday())
            $('#eva_date').datetimepicker({
                minView: "month", //选择日期后，不会再跳转去选择时分秒
                language: 'zh-CN',
                format: 'yyyy-mm-dd',
                todayBtn: true,//今日按钮
                autoclose: true,  //当选择一个日期之后是否立即关闭此日期时间选择器。
                endDate: new Date(), //结束日期为当前日期
                //startDate: new Date("2017/6/15"),  //开始时间
            });
        });

        //编辑按钮
        $("#btn_edit").click(function () {

            seleceedButton = 'edit';

            var arrselections = $("#data_table").bootstrapTable('getSelections');
            //alert(JSON.stringify(arrselections));
            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            } else if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            //若标准状态是废止，不可编辑
            var status = '废止';
            for (var i = 0; i < standardStatus.length; i++) {
                if (standardStatus[i].key == arrselections[0]['evaBasis']) {
                    status = standardStatus[i].value;
                    break;
                }
            }
            if (status == "废止") {
                bootoast({
                    message: '已废止',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            //清空可能为空的输入框
            // $('#eva_unit').val('');
            // $('#eva_person').val('');

            class1Init();
            $('#eva_date').val((arrselections[0]['evaDate']).substring(0, 10));
            $('#company_name').val(arrselections[0]['companyName']);
            $('#class1').val(arrselections[0]['class1']);
            getClass2();
            $('#class2').val(arrselections[0]['class2']);
            $('#company_type').val(arrselections[0]['companyType']);
            getEvaBasis();
            //$('#eva_basis').val(arrselections[0]['evaBasis']);
            if (arrselections[0]['evaBasis'].search("18916.24-2016") != -1) {
                $("#eva_basis option:contains('18916.24-2016')").prop("selected", true);
            } else if (arrselections[0]['evaBasis'].search("18916.25-2016") != -1) {
                $("#eva_basis option:contains('18916.25-2016')").prop("selected", true);
            } else if (arrselections[0]['evaBasis'].search("18916.20-2016") != -1) {
                $("#eva_basis option:contains('18916.20-2016')").prop("selected", true);
            } else if (arrselections[0]['evaBasis'].search("18916.21-2016") != -1) {
                $("#eva_basis option:contains('18916.21-2016')").prop("selected", true);
            } else if (arrselections[0]['evaBasis'].search("18916.14-2014") != -1) {
                $("#eva_basis option:contains('18916.14-2014')").prop("selected", true);
            } else if (arrselections[0]['evaBasis'].search("18916.4-2012") != -1) {
                $("#eva_basis option:contains('18916.4-2012')").prop("selected", true);
            } else {
                $('#eva_basis').val(arrselections[0]['evaBasis']);
            }
            $('#eva_unit').val(arrselections[0]['evaUnit']);
            $('#eva_person').val(arrselections[0]['evaPerson']);
            document.getElementById('title').innerHTML = '编辑一项评价量化标准';
            $('#data').modal()
            //加载时间组件
            $('#eva_date').datetimepicker({
                minView: "month", //选择日期后，不会再跳转去选择时分秒
                language: 'zh-CN',
                format: 'yyyy-mm-dd',
                todayBtn: true,//今日按钮
                autoclose: true,  //当选择一个日期之后是否立即关闭此日期时间选择器。
                endDate: new Date(), //结束日期为当前日期
                //startDate: new Date("2017/6/15"),  //开始时间
            });
        });

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            ids = [];
            for (var i = 0; i < arrselections.length; i++)
                ids.push(arrselections[i].id);
            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/entity_classified_standard/delete",
                            async: false,
                            data: JSON.stringify(ids),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                } else {
                                    bootoast({
                                        message: '删除失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })
        });

        //搜索按钮
        $('#btn_search').click(function () {
            $('#search_content').val("");
            $('#search_data').modal();
        });

        //选择框内的提交
        $('#data_submit').on('click', function () {
            if (seleceedButton == 'add') {
                var companyName = $('#company_name').val()
                var class1 = $('#class1').val()
                var class2 = $('#class2').val()
                var companyType = $('#company_type').val()
                //var evaBasis = $('#eva_basis').val()
                var evaBasis = $("#eva_basis").find("option:selected").text();
                var evaUnit = $('#eva_unit').val()
                var evaPerson = $('#eva_person').val()
                var date = $('#eva_date').val()
                date = date.replace(/-/g, "/");
                var evaDate = new Date(date);

                if (companyName == "" || companyName == null) {
                    bootoast({
                        message: '请输入企业名称',
                        position: 'top',
                        type: 'warning',
                        timeout: 1.5,
                    });
                    return;
                }
                if (class1 == "" || class1 == null) {
                    bootoast({
                        message: '请输入所属行业(大类)',
                        position: 'top',
                        type: 'warning',
                        timeout: 1.5,
                    });
                    return;
                }
                if (class2 == "" || class2 == null) {
                    bootoast({
                        message: '请输入所属行业(小类)',
                        position: 'top',
                        type: 'warning',
                        timeout: 1.5,
                    });
                    return;
                }
                if (companyType == "" || companyType == null) {
                    bootoast({
                        message: '请输入企业类型',
                        position: 'top',
                        type: 'warning',
                        timeout: 1.5,
                    });
                    return;
                }
                if (evaBasis == "" || evaBasis == null) {
                    bootoast({
                        message: '请输入评价依据',
                        position: 'top',
                        type: 'warning',
                        timeout: 1.5,
                    });
                    return;
                }

                $.ajax({
                    type: "post",
                    url: "/entity_classified_standard/insert",
                    async: false,
                    data: {
                        'evaDate': evaDate,
                        'companyName': companyName,
                        'class1': class1,
                        'class2': class2,
                        'companyType': companyType,
                        'evaBasis': evaBasis,
                        'evaUnit': evaUnit,
                        'evaPerson': evaPerson,
                        'state': "填写中",
                        'modifyTime': new Date()
                    },
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '插入成功',
                                position: 'top',
                                type: 'success',
                                timeout: 2,
                            });
                            $("#data").modal('hide');
                            $('#eva_date').val(getToday())
                            $('#company_name').val("")
                            $('#class1').val("")
                            $('#class2').val("")
                            $('#company_type').val("")
                            $('#eva_basis').val("")
                            $('#eva_unit').val("")
                            $('#eva_person').val("")
                            $("#data_table").bootstrapTable('refresh')
                        } else {
                            bootoast({
                                message: '插入失败\n' + data['msg'],
                                position: 'top',
                                type: 'danger',
                                timeout: 2,
                            });
                        }
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            } else if (seleceedButton == 'edit') {
                var id = $("#data_table").bootstrapTable('getSelections')[0]['id'];
                var companyName = $('#company_name').val();
                var class1 = $('#class1').val();
                var class2 = $('#class2').val();
                var companyType = $('#company_type').val();
                //var evaBasis = $('#eva_basis').val();
                var evaBasis = $("#eva_basis").find("option:selected").text();
                var evaUnit = $('#eva_unit').val();
                var evaPerson = $('#eva_person').val();
                var date = $('#eva_date').val();
                date = date.replace(/-/g, "/");
                var evaDate = new Date(date);
                $.ajax({
                    type: "post",
                    url: "/entity_classified_standard/update",
                    async: false,
                    data: {
                        'id': id,
                        'companyName': companyName,
                        'class1': class1,
                        'class2': class2,
                        'companyType': companyType,
                        'evaBasis': evaBasis,
                        'evaUnit': evaUnit,
                        'evaPerson': evaPerson,
                        'evaDate': evaDate,
                        'modifyTime': new Date()
                    },
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '修改成功',
                                position: 'top',
                                type: 'success',
                                timeout: 2,
                            });
                            $("#data").modal('hide');
                            $("#data_table").bootstrapTable('refresh');
                        } else {
                            bootoast({
                                message: '修改失败\n' + data['msg'],
                                position: 'top',
                                type: 'danger',
                                timeout: 2,
                            });
                        }
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            }
        });

        //搜索框内的提交
        $('#search_data_submit').click(function () {
            var ids = [];
            var searchContent = $('#search_content').val();
            var data = $('#data_table').bootstrapTable('getData', false);//获取所有数据
            for (var i = 0; i < data.length; i++) {
                var flag = false;
                for (var prop in data[i]) {
                    if (prop == 'evaDate' || prop == 'companyName' || prop == 'companyType' || prop == 'class1' || prop == 'class2' || prop == 'evaBasis' || prop == 'evaUnit' || prop == 'evaPerson') {
                        if (String(data[i][prop]).indexOf(String(searchContent)) != -1) {
                            //alert(String(data[i][prop]));
                            flag = true;
                            break;
                        }
                    }
                }
                if (!flag) {
                    ids.push(parseInt(data[i]['id']));
                }
            }
            $('#data_table').bootstrapTable('remove', { 'field': 'id', 'values': ids });
            $('#search_data').modal('hide');
        });
    };
    return oInit;
};

var hasPermission = function () {
    queryPermission('取水定额', '编辑', 'btn_edit')
    queryPermission('取水定额', '删除', 'btn_delete')
    queryPermission('取水定额', '新增', 'btn_add')
}

$(function () {

    hasPermission();

    //查询所有标准状态
    getStandardStatus();

    //初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    //隐藏列
    $('#data_table').bootstrapTable('hideColumn', 'id');
    $('#data_table').bootstrapTable('hideColumn', 'class1');

});

//查询所有标准状态
function getStandardStatus() {
    $.ajax({
        url: "/entity_classified_standard/get_standard_status",
        async: false,
        type: "get",
        success: function (result) {
            var list = result['rows'];
            for (var i = 0; i < list.length; i++) {
                standardStatus.push({
                    'key': list[i].standardNum,
                    'value': list[i].standardStatus,
                })
            }
            //console.log(standardStatus);
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

//小函数
//获取当前时期 yyyy-mm-dd
function getToday() {
    var date = new Date();
    var mon = date.getMonth() + 1;         //getMonth()返回的是0-11，则需要加1
    if (mon <= 9) {                                     //如果小于9的话，则需要加上0
        mon = "0" + mon;
    }
    var day = date.getDate();                   //getdate()返回的是1-31，则不需要加1
    if (day <= 9) {                                     //如果小于9的话，则需要加上0
        day = "0" + day;
    }
    var date_info = date.getFullYear() + "-" + mon + "-" + day;
    return date_info;
}

//新增时，将门类加载到选择框
function class1Init() {
    var class1 = document.getElementById("class1");
    class1.options.length = 1;
    for (var e in list) {
        var opt_1 = new Option(list[e].name, list[e].value);
        class1.add(opt_1);
    }
}


//根据门类，选择显示在所属行业选择框的数据
function getClass2() {
    var class1 = document.getElementById("class1");
    var class2 = document.getElementById("class2");
    var evaBasis = document.getElementById("eva_basis");
    var class1Value = class1.value;

    class2.options.length = 1;
    evaBasis.options.length = 1;

    for (var e in list) {
        if (list[e].value == class1Value) {
            for (var p in list[e].class2) {
                var opt_2 = new Option(list[e].class2[p].name, list[e].class2[p].value);
                class2.add(opt_2);
            }
            break;
        }
    }
}

//若选择所属行业之前还没选择门类，弹出提示信息
function class2Check() {
    var inputClass1 = $('#class1').val();
    if (inputClass1 == "" || inputClass1 == null) {
        alert("请先选择门类");
    }
}

function getEvaBasis() {
    //重选class2，将evaBasis置为空
    document.getElementById("eva_basis").options.length = 1;

    $.ajax({
        url: "/entity_classified_standard/get_eva_basis",
        type: "get",
        async: false,
        success: function (result) {
            var inputClass2 = $('#class2').val();
            var list = result['rows'];
            for (var i = 0; i < list.length; i++) {
                if (list[i].class2 == inputClass2) {
                    $("#eva_basis").append("<option value=" + list[i].standardNum + ">" + list[i].standardNum + "</option>");
                }
            }
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

function evaBasisCheck() {
    var inputClass2 = $('#class2').val();
    if (inputClass2 == "" || inputClass2 == null) {
        alert("请先选择所属行业");
    }
}

//临时变量
var entity_classified_standard_id;
var entity_classified_standard_num;
var operation;
var companyType;

//单行函数跳转
function edit(id, standardNum, type) {
    operation = 'edit';
    entity_classified_standard_id = id;
    entity_classified_standard_num = standardNum;
    companyType = type;
    $('#page-wrapper').load('pages/entity_water_count.html');
}

function view(id, standardNum, type) {
    operation = 'view';
    entity_classified_standard_id = id;
    entity_classified_standard_num = standardNum;
    companyType = type;
    $('#page-wrapper').load('pages/entity_water_count.html');
}

//导出
function exportTable(id, standardNum, type) {
    operation = 'export';
    entity_classified_standard_id = id;
    entity_classified_standard_num = standardNum;
    companyType = type;
    $('#page-wrapper').load('pages/entity_water_count.html');
}

